package cn.hzw.supermarket.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.concurrent.ExecutionException;

public abstract class RecyclerViewAdapter<T> extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>
        implements View.OnLongClickListener, View.OnClickListener {

    protected Context context;
    private OnItemLongClickListener onItemLongClickListener;
    private OnItemClickListener onItemClickListener;
    public List<T> datas;

    protected int layoutId;

    //根据viewType返回布局ID
    public abstract int getLayoutId(int viewType);

    //具体的bind操作
    public abstract void convert(ViewHolder holder, T data, int position);

    public interface OnItemClickListener{
        void onItemClick(View v, int pos);
    }

    @Override
    public void onClick(View v) {
        if(onItemClickListener!=null) {
            onItemClickListener.onItemClick(v, (int) v.getTag());
        }
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener){
        this.onItemClickListener = onItemClickListener;
    }

    @Override
    public boolean onLongClick(View v) {
        int originPos = (int) v.getTag();
        return onItemLongClickListener!=null && onItemLongClickListener.onItemLongClick(v, originPos);
    }

    public abstract static class OnItemLongClickListener{
        public abstract boolean onItemLongClick(View v, int pos);
    }

    public void setOnItemLongClickListener(OnItemLongClickListener listener){
        this.onItemLongClickListener = listener;
    }

    public RecyclerViewAdapter(Context context, int layoutId, List<T> datas) {
        this.context = context;
        this.layoutId = layoutId;
        this.datas = datas;
    }

    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(layoutId, parent, false);
        view.setOnLongClickListener(this);
        view.setOnClickListener(this);
        return new ViewHolder(context, view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        convert(holder, datas.get(position), position);
        //设置Tag
        holder.itemView.setTag(position);
    }

    @Override
    public int getItemCount() { return datas.size(); }


    protected static class ViewHolder extends RecyclerView.ViewHolder {
        private Context context;
        private SparseArray<View> mViews;
        private View mConvertView;

        public ViewHolder(Context context, View itemView) {
            super(itemView);
            this.context = context;
            mConvertView = itemView;
            mViews = new SparseArray<>();
        }

        //通过id获得对应的View（首先在mViews中查询是否存在，如果没有，那么findViewById()并放入mViews中，避免下次再执行findViewById()）
        public static ViewHolder get(ViewGroup parent, int layoutId) {
            return new ViewHolder(parent.getContext(),
                    LayoutInflater.from(parent.getContext())
                            .inflate(layoutId, parent, false));
        }

        /**
         * 通过viewId获取控件
         * @param viewId
         * @return
         */
        public <T extends View> T getView(int viewId) {
            View view = mViews.get(viewId);
            if (view==null) {
                view = mConvertView.findViewById(viewId);
                mViews.put(viewId, view);
            }
            return (T)view;
        }

        public ViewHolder setText(int viewId, String text){
            TextView tv = getView(viewId);
            tv.setText(text);
            return this;
        }

        public ViewHolder setImage(int viewId, String imgPath) {
            ImageView view = getView(viewId);
            Glide.with(context).load(imgPath).override(350,350).into(view);
            return this;
        }

        public ViewHolder setOnClickListener(int viewId, View.OnClickListener listener) {
            View view = getView(viewId);
            Log.d("TAG", view.toString());
            view.setOnClickListener(listener);
            return this;
        }

    }
//    public void getDrawableGlide(String pic, CustomTarget<Drawable> customTarget) {
//        Glide.with(context).load(pic).into(customTarget);
//    }
    public static Drawable getDrawablePic(String pic){
        Drawable drawable = null;
        try {
            URL url = new URL(pic);
            URLConnection conn = url.openConnection();
            conn.connect();
            InputStream in;
            in = conn.getInputStream();
            drawable = Drawable.createFromStream(in,"background.jpg");
        }catch (IOException e){
            e.printStackTrace();
        }
        return drawable;
    }
//
    public static void initNetWorkImage(final String url, final Activity context){
        new AsyncTask<Void,Void, Bitmap>(){

            @Override
            public  Bitmap doInBackground(Void... voids) {
                Bitmap bitmap = null;
                try {
                    bitmap = Glide.with(context)
                            .asBitmap()
                            .load(url)
                            .submit(360,480).get();
                }catch (Exception e){
                    e.printStackTrace();
                }
                return bitmap;
            }
        };
    }
}

